<template>
	<view class="publish-page">
		<!-- 顶部导航 -->
		<view class="publish-header">
			<view class="header-left" @click="goBack">
				<u-icon name="arrow-left" size="36px" color="#FFFFFF"></u-icon>
			</view>
			<view class="header-title">发布动态</view>
			<view class="header-right" @click="submitPublish" :class="{'disabled': !canSubmit}">
				<text>发布</text>
			</view>
		</view>

		<!-- 发布内容区域 -->
		<view class="publish-content">
			<!-- 输入框 -->
			<view class="publish-input">
				<textarea v-model="content" :placeholder="'分享' + info + '的学习成果和精彩瞬间...'" class="input-textarea"
					maxlength="500" @input="checkInput"></textarea>
				<view class="placeholder" v-if="!content.length">
					<text>分享{{info}}的学习成果和精彩瞬间...</text>
				</view>
			</view>

			<!-- 图片选择区域 -->
			<view class="image-selector">
			  <view class="selector-title">添加图片</view>
			  <view class="image-grid">
			    <!-- 已选择的图片 -->
			    <view class="image-item" v-if="imageList.length > 0" :key="0"
			      @click="previewPublishImage(imageList[0])">
			      <u-image :src="imageList[0]" mode="aspectFill" width="160rpx" height="160rpx" radius="12rpx"></u-image>
			      <view class="delete-btn" @click.stop="removeImage(0)">
			        <u-icon name="close" size="24rpx" color="#FFFFFF"></u-icon>
			      </view>
			    </view>
			
			    <!-- 图片选择按钮 - 当没有图片时显示 -->
			    <view class="add-image" v-if="imageList.length === 0" @click="chooseImage">
			      <u-icon name="plus" size="36rpx" color="#2C57F6"></u-icon>
			      <text>添加图片</text>
			    </view>
			  </view>
			</view>

			<!-- 孩子信息选择 -->
			<view class="child-selector">
				<view class="selector-title">选择{{info}}</view>
				<view class="child-list" @click="openChildSelector">
					<view class="child-item" v-if="selectedChild">
						<u-avatar :src="selectedChild.stuUrl" size="70rpx"></u-avatar>
						<view class="child-info">
							<view class="child-name">{{selectedChild.stuName||''}}</view>
							<view class="child-class">{{selectedChild.claDescribe}}</view>
						</view>
						<u-icon name="arrow-right" size="28rpx" color="#999999"></u-icon>
					</view>
					<view class="child-placeholder" v-else>
						<text>请选择孩子</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部提示 -->
		<view class="publish-tip">
			<text>最多可添加9张图片，发布内容将展示在社区中</text>
		</view>

		<!-- 孩子选择弹窗 -->
		<view class="child-selector-modal" v-if="childModalVisible" @click="closeChildModal">
			<view class="child-selector-content" @click.stop>
				<view class="child-selector-header">
					<view class="title">选择{{info}}</view>
					<view class="close-btn" @click="closeChildModal">
						<u-icon name="close" size="32rpx" color="#999"></u-icon>
					</view>
				</view>
				<view class="child-list-container">
					<view class="child-select-item" v-for="(child, index) in childList" :key="index"
						@click="selectChild(child)"
						:class="{'selected': selectedChild && selectedChild.claId === child.claId&& selectedChild.stuId === child.stuId}">
						<u-avatar :src="child.stuUrl" size="80rpx" v-show="isShow"></u-avatar>
						<view class="child-info">
							<view class="child-name" v-show="isShow">{{child.stuName}}</view>
							<view class="child-class">{{child.claDescribe}}</view>
						</view>
						<u-icon
							v-if="selectedChild && selectedChild.claId === child.claId&&selectedChild.stuId === child.claId&& selectedChild.stuId === child.stuId"
							name="checkmark" size="32rpx" color="#2C57F6"></u-icon>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		queryUserList,acceptTheDynamics
	} from '@/api/community.js'
	export default {
		data() {
			return {
				user: {
					parentId: 1003,
					teacherId: 0,
					campusId: 1,
				},
				updaloadUrl:'http://localhost:5217/community/uploadImage',
				isShow: true,
				content: '', // 发布内容
				imageList: [], // 选择的图片列表
				selectedChild: null, // 选择的孩子信息
				childList: [ ],//孩子列表数据
				canSubmit: false, // 是否可以提交
				childModalVisible: false, // 孩子选择弹窗是否显示
				info: '班级孩子',
				imagePath:'',
				
			}
		},
		created() {
			if (this.user.parentId == 0 && this.user.teacherId != 0) {
				this.info = '班级';
				this.isShow = false;
			}
		},
		onLoad() {
			this.handleQueryChildList();



		},
		methods: {
			// 单张图片上传
			uploadImageToServer(tempFilePath) {
			  return new Promise((resolve, reject) => {
			    uni.uploadFile({
			      url: this.updaloadUrl, // 服务器上传接口
			      filePath: tempFilePath,
			      name: 'file',
			      success: (res) => {
					  
			        const data = JSON.parse(res.data);
					
			        if (data.code === 200) resolve(data.data.path);
			        else reject(new Error(data.message));
			      },
			      fail: (err) => reject(err)
			    });
			  });
			  },
			// 封装默认选中逻辑
			setDefaultSelectedChild() {
				if (this.childList.length > 0 && !this.selectedChild) {
					this.selectedChild = this.childList[0];
					console.log("默认选中孩子:", this.selectedChild);
				}
			},
			//查询当前孩子列表
			handleQueryChildList() {
				console.log("查询孩子列表");
				const data = {
					campusId: this.user.campusId,
					parentId: this.user.parentId || 0,
					teacherId: this.user.teacherId || 0,
				}
				queryUserList(data).then(res => {
					console.log(res);
					this.childList = res.data.userList;
					this.setDefaultSelectedChild();
				}).catch(err => {
					console.log("查询列表出错");
				})
			},
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},

			// 检查输入内容，确定是否可以提交
			checkInput() {
				// 内容不为空 或者 有图片时可以提交
				this.canSubmit = this.content.trim().length > 0 || this.imageList.length > 0;
			},
			
			// 提交发布
			async submitPublish() {
				if (!this.canSubmit) return;

				uni.showLoading({
					title: '发布中...'
				});				
				// 检查是否有图片需要上传
				let mesPath='';
				  if (this.imageList.length > 0) {
				    try {
				      mesPath = await this.uploadImageToServer(this.imageList[0]);
				      console.log("mes的值为：",mesPath);
				    } catch (error) {
				      uni.showToast({ title: '图片上传失败', icon: 'none' });
				      uni.hideLoading();
				      return;
				    }}
				
				const data = {
					parentId:this.user.parentId||0,
					teacherId:this.user.teacherId||0,
					mesPath:mesPath||0,
					claId:this.selectedChild.claId,
					campusId:this.user.campusId,
					stuId:this.selectedChild.stuId||0,
					mesContent:this.content,
				};
				console.log(data);
				acceptTheDynamics(data).then(res=>{
					console.log(res);
					if(res.data.status>0){
						uni.showToast({
							title: res.message,
							icon: 'success'
						});
					}else{
						uni.showToast({
							title: res.message,
							icon: 'error'
						});
					}
				}).catch(err=>{
					console.log("发布动态失败");
				})
				setTimeout(() => {
					uni.hideLoading();
					// 返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				}, 1500);
			},

			// 选择图片
			chooseImage() {
				if (this.imageList.length >= 1) {
					uni.showToast({
						title: '最多只能添加1张图片',
						icon: 'none'
					});
					return;
				}

				uni.chooseImage({
					count: 1 - this.imageList.length,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						this.imageList = res.tempFilePaths;
						this.checkInput();
					}
				});
			},

			// 移除图片
			removeImage(index) {
				 this.imageList = []; 
				  this.checkInput();
			},

			// 预览发布图片
			previewPublishImage(img) {
				uni.previewImage({
					current: img,
					urls: this.imageList
				});
			},

			// 打开孩子选择器
			openChildSelector() {
				this.childModalVisible = true;
			},

			// 关闭孩子选择弹窗
			closeChildModal() {
				this.childModalVisible = false;
			},

			// 选择孩子
			selectChild(child) {
				this.selectedChild = child;
				this.closeChildModal();
				this.checkInput(); // 检查是否可以提交
			},
			// 将临时文件路径转换为File对象
			    convertTempFileToFile(tempFilePath) {
			      return new Promise((resolve, reject) => {
			        uni.getFileSystemManager().readFile({
			          filePath: tempFilePath,
			          encoding: 'base64',
			          success: (res) => {
			            const base64Data = res.data;
			          
			            const byteCharacters = atob(base64Data);
			            const byteArrays = [];
			            for (let i = 0; i < byteCharacters.length; i++) {
			              const byteChar = byteCharacters.charAt(i);
			              byteArrays.push(byteChar.charCodeAt(0));
			            }
			            const blob = new Blob([new Uint8Array(byteArrays)], {
			              type: tempFilePath.split('.').pop() || 'image/jpeg'
			            });
			            
			            
			            const fileName = tempFilePath.split('/').pop();
			            const file = new File([blob], fileName, { type: blob.type });
			            resolve(file);
			          },
			          fail: (err) => {
			            reject(err);
			          }
			        });
			      });
			    },
		}
	}
</script>

<style lang="scss" scoped>
	.publish-page {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #F5F7FA;

		.publish-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 30rpx;
			height: 120rpx;
			background-color: #2C57F6;
			color: #FFFFFF;
			font-size: 36rpx;
			font-weight: bold;

			.header-left,
			.header-right {
				width: 80rpx;
				height: 80rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.header-right {
				color: #FFFFFF;
				opacity: 0.5;

				&.disabled {
					opacity: 0.5;
					pointer-events: none;
				}

				&:not(.disabled) {
					opacity: 1;
				}
			}
		}

		.publish-content {
			flex: 1;
			padding: 30rpx;
			box-sizing: border-box;

			.publish-input {
				background-color: #FFFFFF;
				border-radius: 16rpx;
				padding: 20rpx 30rpx;
				margin-bottom: 30rpx;
				position: relative;

				.input-textarea {
					width: 100%;
					height: 240rpx;
					font-size: 28rpx;
					line-height: 1.5;
					border: none;
					outline: none;
				}

				.placeholder {
					position: absolute;
					top: 20rpx;
					left: 30rpx;
					color: #999999;
					font-size: 28rpx;
					line-height: 1.5;
				}
			}

			.image-selector,
			.child-selector {
				background-color: #FFFFFF;
				border-radius: 16rpx;
				padding: 30rpx;
				margin-bottom: 30rpx;

				.selector-title {
					font-size: 28rpx;
					color: #333333;
					margin-bottom: 20rpx;
				}
			}

			.image-grid {
				display: flex;
				flex-wrap: wrap;
			}

			.image-item,
			.add-image {
				width: 160rpx;
				height: 160rpx;
				margin-right: 20rpx;
				margin-bottom: 20rpx;
				position: relative;
				border-radius: 12rpx;
				background-color: #F5F7FA;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.image-item {
				background-color: #FFFFFF;
			}

			.add-image {
				border: 1px dashed #DDDDDD;
				flex-direction: column;
				justify-content: center;
			}

			.add-image text {
				margin-top: 10rpx;
				font-size: 24rpx;
				color: #999999;
			}

			.delete-btn {
				position: absolute;
				top: -10rpx;
				right: -10rpx;
				width: 40rpx;
				height: 40rpx;
				border-radius: 50%;
				background-color: rgba(0, 0, 0, 0.5);
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.child-list {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.child-item {
					display: flex;
					align-items: center;

					.child-info {
						margin-left: 20rpx;

						.child-name {
							font-size: 28rpx;
							color: #333333;
						}

						.child-class {
							font-size: 24rpx;
							color: #999999;
							margin-top: 4rpx;
						}
					}
				}

				.child-placeholder {
					font-size: 28rpx;
					color: #999999;
				}
			}
		}

		.publish-tip {
			padding: 20rpx 30rpx;
			font-size: 24rpx;
			color: #999999;
			text-align: center;
		}

		/* 孩子选择弹窗样式 */
		.child-selector-modal {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(0, 0, 0, 0.5);
			display: flex;
			justify-content: center;
			align-items: center;
			z-index: 1000;
			animation: fadeIn 0.3s;
		}

		.child-selector-content {
			background-color: #FFFFFF;
			border-radius: 20rpx;
			width: 85%;
			max-height: 80vh;
			overflow-y: auto;
			padding: 30rpx;
			box-sizing: border-box;
			position: relative;
			animation: slideUp 0.3s;
		}

		.child-selector-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;

			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}

			.close-btn {
				font-size: 32rpx;
				color: #999;
			}
		}

		.child-list-container {
			.child-select-item {
				display: flex;
				align-items: center;
				padding: 24rpx 0;
				border-bottom: 1rpx solid #F5F7FA;

				&:last-child {
					border-bottom: none;
				}

				.u-avatar {
					margin-right: 24rpx;
				}

				.child-info {
					flex: 1;

					.child-name {
						font-size: 28rpx;
						color: #333;
						font-weight: 500;
					}

					.child-class {
						font-size: 24rpx;
						color: #999;
						margin-top: 6rpx;
					}
				}

				.u-icon.checkmark {
					margin-left: 24rpx;
				}

				&.selected {
					.child-name {
						color: #2C57F6;
					}

					.child-class {
						color: #66B1FF;
					}
				}
			}
		}

		/* 动画效果 */
		@keyframes fadeIn {
			from {
				opacity: 0;
			}

			to {
				opacity: 0.5;
			}
		}

		@keyframes slideUp {
			from {
				transform: translateY(30%);
				opacity: 0;
			}

			to {
				transform: translateY(0);
				opacity: 1;
			}
		}
	}
</style>